"""
摄像头管理API端点
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from core.database import get_db
from services.core.camera_service import CameraService
from schemas.camera import (
    CameraCreate, CameraUpdate, CameraResponse, CameraListResponse,
    CameraFilters, CameraStatus, CameraStatusUpdate, CameraConnectionTest,
    BatchStatusUpdate, BatchUpdateRequest, CameraHealthCheck, 
    SystemHealthSummary, StatisticsSummary
)
from utils.response import APIResponse
from core.exceptions import (
    CameraNotFoundError, CameraDuplicateError, CameraValidationError,
    CameraConnectionError, ValidationError, BusinessRuleError
)
import structlog

logger = structlog.get_logger(__name__)
router = APIRouter()


def get_camera_service(db: Session = Depends(get_db)) -> CameraService:
    """获取摄像头服务实例"""
    return CameraService(db)


@router.post("", response_model=APIResponse[CameraResponse], status_code=status.HTTP_201_CREATED)
async def create_camera(
    camera_data: CameraCreate,
    service: CameraService = Depends(get_camera_service)
):
    """
    创建摄像头
    
    - **name**: 设备名称（必填，唯一）
    - **location**: 安装位置
    - **latitude**: 纬度（-90到90）
    - **longitude**: 经度（-180到180）
    - **rtsp_url**: RTSP地址（必填，以rtsp://开头）
    - **wvp_device_id**: WVP-Pro设备ID
    - **wvp_channel_id**: WVP-Pro通道ID
    - **ai_enabled**: 是否启用AI分析
    - **description**: 设备描述
    """
    # 使用新的异常处理系统，异常会被全局处理器自动捕获和处理
    camera = await service.create_camera(camera_data)
    logger.info("摄像头创建成功", camera_id=camera.id, name=camera.name)
    
    return APIResponse(
        code=201,
        message="摄像头创建成功",
        data=CameraResponse.model_validate(camera)
    )


@router.get("", response_model=APIResponse[CameraListResponse])
async def list_cameras(
    name: str = Query(None, description="设备名称筛选"),
    location: str = Query(None, description="位置筛选"),
    status: CameraStatus = Query(None, description="状态筛选"),
    ai_enabled: bool = Query(None, description="AI启用状态筛选"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    service: CameraService = Depends(get_camera_service)
):
    """
    获取摄像头列表
    
    支持按名称、位置、状态、AI启用状态筛选，支持分页
    """
    try:
        filters = CameraFilters(
            name=name,
            location=location,
            status=status,
            ai_enabled=ai_enabled,
            page=page,
            size=size
        )
        
        result = service.get_camera_list(filters)
        
        return APIResponse(
            code=200,
            message="获取摄像头列表成功",
            data=result
        )
    except Exception as e:
        logger.error("获取摄像头列表异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取摄像头列表失败"
        )


@router.get("/{camera_id}", response_model=APIResponse[CameraResponse])
async def get_camera(
    camera_id: int,
    service: CameraService = Depends(get_camera_service)
):
    """
    获取摄像头详情
    """
    camera = service.get_camera(camera_id)
    if not camera:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="摄像头不存在"
        )
    
    return APIResponse(
        code=200,
        message="获取摄像头详情成功",
        data=CameraResponse.model_validate(camera)
    )


@router.put("/{camera_id}", response_model=APIResponse[CameraResponse])
async def update_camera(
    camera_id: int,
    camera_data: CameraUpdate,
    service: CameraService = Depends(get_camera_service)
):
    """
    更新摄像头信息
    """
    try:
        camera = await service.update_camera(camera_id, camera_data)
        if not camera:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="摄像头不存在"
            )
        
        logger.info("摄像头更新成功", camera_id=camera_id)
        
        return APIResponse(
            code=200,
            message="摄像头更新成功",
            data=CameraResponse.model_validate(camera)
        )
    except ValueError as e:
        logger.warning("摄像头更新失败", camera_id=camera_id, error=str(e))
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error("摄像头更新异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="摄像头更新失败"
        )


@router.delete("/{camera_id}", response_model=APIResponse[bool])
async def delete_camera(
    camera_id: int,
    service: CameraService = Depends(get_camera_service)
):
    """
    删除摄像头
    """
    try:
        success = service.delete_camera(camera_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="摄像头不存在"
            )
        
        logger.info("摄像头删除成功", camera_id=camera_id)
        
        return APIResponse(
            code=200,
            message="摄像头删除成功",
            data=True
        )
    except Exception as e:
        logger.error("摄像头删除异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="摄像头删除失败"
        )


@router.post("/{camera_id}/test", response_model=APIResponse[CameraConnectionTest])
async def test_camera_connection(
    camera_id: int,
    service: CameraService = Depends(get_camera_service)
):
    """
    测试摄像头连接
    """
    try:
        test_result = await service.test_camera_connection(camera_id)
        
        return APIResponse(
            code=200,
            message="连接测试完成",
            data=test_result
        )
    except Exception as e:
        logger.error("摄像头连接测试异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="连接测试失败"
        )


@router.put("/{camera_id}/status", response_model=APIResponse[CameraResponse])
async def update_camera_status(
    camera_id: int,
    status_data: CameraStatusUpdate,
    service: CameraService = Depends(get_camera_service)
):
    """
    更新摄像头状态
    """
    try:
        camera = service.update_camera_status(camera_id, status_data.status)
        if not camera:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="摄像头不存在"
            )
        
        logger.info("摄像头状态更新成功", camera_id=camera_id, status=status_data.status)
        
        return APIResponse(
            code=200,
            message="摄像头状态更新成功",
            data=CameraResponse.model_validate(camera)
        )
    except Exception as e:
        logger.error("摄像头状态更新异常", camera_id=camera_id, exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="摄像头状态更新失败"
        )


@router.get("/statistics/overview", response_model=APIResponse[dict])
async def get_camera_statistics(
    service: CameraService = Depends(get_camera_service)
):
    """
    获取摄像头统计信息
    """
    try:
        stats = service.get_camera_statistics()
        
        return APIResponse(
            code=200,
            message="获取统计信息成功",
            data=stats
        )
    except Exception as e:
        logger.error("获取摄像头统计信息异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取统计信息失败"
        )


@router.post("/batch/test", response_model=APIResponse[List[dict]])
async def batch_test_cameras(
    camera_ids: List[int],
    service: CameraService = Depends(get_camera_service)
):
    """
    批量测试摄像头连接
    """
    try:
        results = await service.batch_test_connections(camera_ids)
        
        return APIResponse(
            code=200,
            message="批量连接测试完成",
            data=results
        )
    except Exception as e:
        logger.error("批量摄像头连接测试异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="批量连接测试失败"
        )


@router.post("/refresh/status", response_model=APIResponse[dict])
async def refresh_all_camera_status(
    service: CameraService = Depends(get_camera_service)
):
    """
    刷新所有摄像头状态
    """
    try:
        result = await service.refresh_all_camera_status()
        
        return APIResponse(
            code=200,
            message="摄像头状态刷新完成",
            data=result
        )
    except Exception as e:
        logger.error("刷新摄像头状态异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="刷新摄像头状态失败"
        )


@router.get("/3d-format", response_model=APIResponse[List[dict]])
async def get_cameras_for_3d(
    service: CameraService = Depends(get_camera_service)
):
    """
    获取3D前端格式的摄像头数据
    
    返回适用于3D场景显示的摄像头数据格式
    """
    try:
        # 获取所有摄像头
        filters = CameraFilters(page=1, size=1000)  # 获取所有摄像头
        camera_list = service.get_camera_list(filters)
        
        # 转换为3D格式
        cameras_3d = []
        for camera_response in camera_list.items:
            # 从数据库获取完整的摄像头对象
            camera = service.get_camera(camera_response.id)
            if camera:
                cameras_3d.append(camera.to_3d_format())
        
        logger.info("获取3D格式摄像头数据成功", count=len(cameras_3d))
        
        return APIResponse(
            code=200,
            message="获取3D格式摄像头数据成功",
            data=cameras_3d
        )
    except Exception as e:
        logger.error("获取3D格式摄像头数据异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取3D格式摄像头数据失败"
        )


# Task 4.3 - Statistics and Management Endpoints

@router.get("/statistics/summary", response_model=APIResponse[dict])
async def get_statistics_summary(
    detailed: bool = Query(False, description="是否返回详细统计信息"),
    service: CameraService = Depends(get_camera_service)
):
    """
    获取摄像头统计信息摘要
    
    返回系统中摄像头的综合统计信息，包括：
    - 总数和状态分布
    - AI启用情况
    - 位置分布
    - 性能指标
    - 健康状况摘要
    """
    try:
        if detailed:
            stats = service.get_comprehensive_statistics(include_trends=True)
        else:
            stats = service.get_camera_statistics(detailed=False)
        
        # 添加健康摘要
        health_summary = service.get_camera_health_summary()
        stats["health_summary"] = health_summary
        
        logger.info("获取统计信息摘要成功", detailed=detailed)
        
        return APIResponse(
            code=200,
            message="获取统计信息摘要成功",
            data=stats
        )
    except Exception as e:
        logger.error("获取统计信息摘要异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取统计信息摘要失败"
        )


@router.post("/batch/status-update", response_model=APIResponse[dict])
async def batch_update_camera_status(
    batch_request: BatchStatusUpdate,
    service: CameraService = Depends(get_camera_service)
):
    """
    批量更新摄像头状态
    
    支持同时更新多个摄像头的状态，适用于：
    - 批量维护操作
    - 系统故障恢复
    - 状态同步
    """
    try:
        # 准备批量更新数据
        updates = []
        for camera_id in batch_request.camera_ids:
            updates.append({
                "id": camera_id,
                "status": batch_request.status,
                "reason": batch_request.reason
            })
        
        # 执行批量更新
        results = await service.batch_update_cameras(updates, validate_all=True)
        
        # 统计结果
        success_count = sum(1 for r in results if r.get("success", False))
        total_count = len(batch_request.camera_ids)
        
        logger.info("批量状态更新完成", 
                   total=total_count, 
                   success=success_count, 
                   status=batch_request.status)
        
        return APIResponse(
            code=200,
            message=f"批量状态更新完成，成功更新 {success_count}/{total_count} 个摄像头",
            data={
                "total_count": total_count,
                "success_count": success_count,
                "failed_count": total_count - success_count,
                "target_status": batch_request.status,
                "results": results
            }
        )
    except Exception as e:
        logger.error("批量状态更新异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="批量状态更新失败"
        )


@router.get("/health/check", response_model=APIResponse[dict])
async def perform_health_check(
    include_details: bool = Query(True, description="是否包含详细检查结果"),
    service: CameraService = Depends(get_camera_service)
):
    """
    执行摄像头系统健康检查
    
    检查项目包括：
    - 摄像头连接状态
    - 数据一致性
    - 系统性能指标
    - 潜在问题识别
    """
    try:
        # 执行系统健康检查
        health_report = service.perform_system_health_check()
        
        if include_details:
            # 添加数据一致性检查
            consistency_check = service.check_data_consistency()
            health_report["data_consistency"] = consistency_check
            
            # 添加性能指标
            performance_metrics = service.get_performance_metrics(hours=1)
            health_report["performance_metrics"] = performance_metrics
        
        # 计算整体健康评分
        overall_score = health_report.get("overall_health_score", 0)
        
        if overall_score >= 90:
            message = "系统健康状况良好"
        elif overall_score >= 70:
            message = "系统健康状况一般，建议关注警告项"
        else:
            message = "系统健康状况较差，需要立即处理"
        
        logger.info("健康检查完成", 
                   overall_score=overall_score, 
                   include_details=include_details)
        
        return APIResponse(
            code=200,
            message=message,
            data=health_report
        )
    except Exception as e:
        logger.error("健康检查异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="健康检查失败"
        )


@router.get("/health/summary", response_model=APIResponse[dict])
async def get_health_summary(
    service: CameraService = Depends(get_camera_service)
):
    """
    获取摄像头健康状况摘要
    
    快速获取系统健康状况概览，包括：
    - 总体健康评分
    - 关键指标
    - 警告和错误统计
    """
    try:
        health_summary = service.get_camera_health_summary()
        
        return APIResponse(
            code=200,
            message="获取健康摘要成功",
            data=health_summary
        )
    except Exception as e:
        logger.error("获取健康摘要异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取健康摘要失败"
        )


@router.post("/management/batch-update", response_model=APIResponse[dict])
async def batch_update_cameras(
    batch_request: BatchUpdateRequest,
    service: CameraService = Depends(get_camera_service)
):
    """
    批量更新摄像头信息
    
    支持批量更新多个摄像头的各种属性，包括：
    - 基本信息（名称、位置等）
    - 配置参数
    - AI算法设置
    """
    try:
        results = await service.batch_update_cameras(
            batch_request.updates, 
            validate_all=batch_request.validate_all
        )
        
        # 统计结果
        success_count = sum(1 for r in results if r.get("success", False))
        total_count = len(batch_request.updates)
        
        logger.info("批量更新完成", 
                   total=total_count, 
                   success=success_count)
        
        return APIResponse(
            code=200,
            message=f"批量更新完成，成功更新 {success_count}/{total_count} 个摄像头",
            data={
                "total_count": total_count,
                "success_count": success_count,
                "failed_count": total_count - success_count,
                "results": results
            }
        )
    except Exception as e:
        logger.error("批量更新异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="批量更新失败"
        )


@router.get("/statistics/ai-algorithms", response_model=APIResponse[dict])
async def get_ai_algorithm_statistics(
    service: CameraService = Depends(get_camera_service)
):
    """
    获取AI算法使用统计
    
    返回各种AI算法的使用情况统计，包括：
    - 启用算法的摄像头数量
    - 算法性能指标
    - 使用趋势分析
    """
    try:
        ai_stats = service.get_ai_algorithm_statistics()
        
        return APIResponse(
            code=200,
            message="获取AI算法统计成功",
            data=ai_stats
        )
    except Exception as e:
        logger.error("获取AI算法统计异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取AI算法统计失败"
        )


@router.get("/statistics/service", response_model=APIResponse[dict])
async def get_service_statistics(
    service: CameraService = Depends(get_camera_service)
):
    """
    获取服务统计信息
    
    返回摄像头服务的运行统计，包括：
    - 服务调用次数
    - 响应时间统计
    - 错误率统计
    - 资源使用情况
    """
    try:
        service_stats = service.get_service_statistics()
        
        return APIResponse(
            code=200,
            message="获取服务统计成功",
            data=service_stats
        )
    except Exception as e:
        logger.error("获取服务统计异常", exc_info=e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取服务统计失败"
        )